package edu.hebtu.mapper.impl;

import edu.hebtu.mapper.IUserMapper;
import edu.hebtu.pojo.User;
import edu.hebtu.util.autoIdUtil;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

//用户
@Mapper
@Repository
public class UserMapper {


    private final IUserMapper IUserMapper;

    @Autowired
    public UserMapper(IUserMapper IUserMapper) {
        this.IUserMapper = IUserMapper;
    }
//    @Autowired
//    private IUserMapper IUserMapper;


    /**
     * 查找正在使用的记录，如果 id = null 则查找所有
     * @param id
     * @return
     */
    public List<User> findById(String id) {
        System.out.println("ClassPath : edu.hebtu.mapper.UserMapper.findUserById");
        List<User> list = IUserMapper.findById(id);
        //移除"disappear"的数据
        list.removeIf(aValue -> aValue.getState().trim().equals("disappear"));
        return list;
    }

    /**
     * 查找未在使用的所有记录
     * @return
     */
    public List<User> findDeleted() {
        System.out.println("ClassPath : edu.hebtu.mapper.UserMapper.findDeleted");
        List<User> list = IUserMapper.findById(null);
        //移除非"disappear"的数据
        list.removeIf(aValue -> !aValue.getState().trim().equals("disappear"));
        return list;
    }

    /**
     * 添加
     * @param object
     * @return
     */
    public int add(User object) {
        System.out.println("ClassPath : edu.hebtu.mapper.UserMapper.addUser");
        List<User> list = IUserMapper.findById(null);
        User o = null;
        String id = null;
        if (list.size() > 0) o = list.get(list.size() - 1);
        if (o != null) id = o.getUserId();
        object.setUserId(autoIdUtil.autoId(id, "u"));       //userId以'u'开头
        object.setState("appear");
        object.setCreateDate(new Date());
        try {
            IUserMapper.add(object);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    /**
     * 修改
     * @param object
     * @return
     */
    public int update(User object) {
        System.out.println("ClassPath : edu.hebtu.mapper.UserMapper.updateUser");
        try {
            IUserMapper.update(object);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    /**
     * 删除(修改状态位为'disappear')
     * @param object
     * @return
     */
    public int delete(User object) {
        System.out.println("ClassPath : edu.hebtu.mapper.UserMapper.deleteUser");
        try {
            object.setState("disappear");
            IUserMapper.update(object);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

}
